//
//  StartOneViewController.m
//  yinsiwenzhen
//
//  Created by Yangfan on 14/12/24.
//  Copyright (c) 2014年 4gread. All rights reserved.
//

#import "StartOneViewController.h"

@interface StartOneViewController ()

@end

@implementation StartOneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBar.tintColor = HexRGB(0x2AADEA);
    self.navigationItem.rightBarButtonItem.tintColor = HexRGB(0xf00);
    [self.navigationItem.rightBarButtonItem setEnabled:NO];
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] init];
    backItem.title = @"第一步";
    self.navigationItem.backBarButtonItem = backItem;
    
    listView = [[ListView alloc] init];
    selectImage = 123456;
    
    [self UIFourImages];
    
    fourImageShow = [[UIScrollView alloc] init];
    [fourImageShow setFrame:CGRectMake(0, 0, Kwidth, Kheight)];
    [fourImageShow setBackgroundColor:[UIColor blackColor]];
    [fourImageShow setPagingEnabled:YES];
    [fourImageShow setHidden: YES];
    [self.navigationController.view addSubview:fourImageShow];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [fourImageShow addGestureRecognizer:tapGesture];
    
    // w为iPhone4做的说明文字适配
    if (isiphone4) {
        [_topTitleForiPhone4 removeFromSuperview];
        _topTitleForiPhone4 = [[UILabel alloc] init];
        [_topTitleForiPhone4 setFrame:CGRectMake(34, 64, Kwidth - 68, 62)];
        _topTitleForiPhone4.text = @"如果需要，建议多角度拍摄患处照片，最少一张";
        _topTitleForiPhone4.font = [UIFont systemFontOfSize:17];
        _topTitleForiPhone4.textColor = HexRGB(0x2AADEA);
        _topTitleForiPhone4.numberOfLines = 0;
        [self.view addSubview:_topTitleForiPhone4];
    }
}

- (void)UIFourImages {
    UIView *cellView;
    float viewWidth;
    if (isiphone6plus) {
        viewWidth = (Kwidth - 34 * 2 - 38) / 2.0;
    } else {
        viewWidth = (Kwidth - 34 * 2 - 28) / 2.0;
    }
    float viewHeight = viewWidth;

    int currentNum = 0;
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            cellView = [[UIView alloc] init];
            cellView.tag = 1111 + currentNum;
            if (isiphone6plus) {
                cellView.frame = CGRectMake(34 + (viewWidth + 38) * j,  64 + 77 + (viewHeight + 39) * i, viewWidth, viewHeight);
            } else {
                if (isiphone4) {
                    cellView.frame = CGRectMake(34 + (viewWidth + 28) * j,  64 + 62 + (viewHeight + 28) * i, viewWidth, viewHeight);
                } else {
                    cellView.frame = CGRectMake(34 + (viewWidth + 28) * j,  64 + 77 + (viewHeight + 28) * i, viewWidth, viewHeight);
                }
            }
            [cellView setBackgroundColor:[UIColor clearColor]];
            [self.view addSubview:cellView];
            
            UIImageView *image = [[UIImageView alloc] init];
            image.tag = 11 + currentNum;
            [image setUserInteractionEnabled:YES];
            [image setFrame:CGRectMake(0, 0, viewWidth, viewHeight)];
            [image setContentMode:UIViewContentModeScaleAspectFill];
            image.clipsToBounds = YES;
            image.image = [UIImage imageNamed:@"noImage"];
            [cellView addSubview:image];
            
            CGRect rect = cellView.frame;
            
            // 添加图片按钮
            UIButton *addImage = [[UIButton alloc] init];
            addImage.tag = 22 + currentNum;
            [addImage setFrame:CGRectMake(0, 8.0 / 23.0 * viewHeight, viewWidth, 7.0 / 23.0 * viewHeight)];
            [addImage setBackgroundImage:[UIImage imageNamed:@"dianjishangchuan"] forState:UIControlStateNormal];
            [addImage setBackgroundImage:[UIImage imageNamed:@"dianjishangchuan"] forState:UIControlStateHighlighted];
            [addImage addTarget:self action:@selector(addOneImage:) forControlEvents:UIControlEventTouchUpInside];
            [cellView addSubview:addImage];
            
            // 删除图片按钮
            UIButton *delete = [[UIButton alloc] init];
            [delete setHidden:YES];
            delete.tag = 2222 + currentNum;
            [delete setFrame:CGRectMake(rect.origin.x + viewWidth - 26, rect.origin.y, 26, 26)];
            [delete setBackgroundImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
            [delete setBackgroundImage:[UIImage imageNamed:@"delete"] forState:UIControlStateHighlighted];
            [delete addTarget:self action:@selector(deleteOneImage:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:delete];
            
            currentNum++;
        }
    }
    
    // 示例图片按钮  (因为项目更改，此按钮已经不再使用)
    /*
    UIButton *exampleButton = [[UIButton alloc] init];
    if (isiphone6plus) {
        [exampleButton setFrame:CGRectMake(34, cellView.frame.origin.y + cellView.frame.size.height + 36, Kwidth - 34 * 2, (Kwidth - 34 * 2) * 68.0 / 344.0)];
    } else {
        if (isiphone4) {
            [exampleButton setFrame:CGRectMake(34, cellView.frame.origin.y + cellView.frame.size.height + 18, Kwidth - 34 * 2, (Kwidth - 34 * 2) * 68.0 / 344.0)];
        } else {
            [exampleButton setFrame:CGRectMake(34, cellView.frame.origin.y + cellView.frame.size.height + 28, Kwidth - 34 * 2, (Kwidth - 34 * 2) * 68.0 / 344.0)];
        }
    }
    [exampleButton setBackgroundImage:[UIImage imageNamed:@"exampleButton"] forState:UIControlStateNormal];
    [exampleButton setBackgroundImage:[UIImage imageNamed:@"exampleButton"] forState:UIControlStateHighlighted];
    [exampleButton addTarget:self action:@selector(actionExample:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exampleButton];
     */
    
    // 下面的四张示例图片
    UIView *blueLine = [[UIView alloc] init];
    [blueLine setBackgroundColor:HexRGB(0x60cbfd)];
    [self.view addSubview:blueLine];
    if (isiphone6plus) {
        [blueLine setFrame:CGRectMake(32, cellView.frame.origin.y + cellView.frame.size.height + 40, Kwidth - 32 * 2, 1)];
    } else {
        if (isiphone4) {
            [blueLine setFrame:CGRectMake(30, cellView.frame.origin.y + cellView.frame.size.height + 14, Kwidth - 30 * 2, 1)];
        } else {
            [blueLine setFrame:CGRectMake(30, cellView.frame.origin.y + cellView.frame.size.height + 31, Kwidth - 30 * 2, 1)];
        }
    }
    
    UIImageView *cellImageView;// 下面的四个示例图片
    // 半透明蒙层
    UILabel *exampleWord;
    // 添加按钮用于看大图
    UIButton *bigImageButton;
    float lineBottom = blueLine.frame.origin.y + blueLine.frame.size.height;
    for (int i = 0; i < 4; i++) {
        cellImageView = [[UIImageView alloc] init];
        if (isiphone6plus) {
            [cellImageView setFrame:CGRectMake(34 + 89 * i, lineBottom + 16, 80, 80)];
        } else {
            [cellImageView setFrame:CGRectMake(34 + ((Kwidth - 68 - 20)/4.0 + 7) * i, lineBottom + 10, (Kwidth - 68 - 20)/4.0, (Kwidth - 68 - 20)/4.0)];
        }
        
        [cellImageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"example%d", i + 1]]];
        [cellImageView setUserInteractionEnabled:YES];
        [self.view addSubview:cellImageView];
        
        
        CGRect rect = cellImageView.frame;
        rect.origin.x = 0;
        rect.origin.y = 0;
        
        exampleWord = [[UILabel alloc] init];
        [exampleWord setFrame:rect];
        [exampleWord setBackgroundColor:HexRGBAlpha(0x60cbfd, 0.4)];
        switch (i) {
            case 0:
                exampleWord.text = @"照";
                break;
            case 1:
                exampleWord.text = @"片";
                break;
            case 2:
                exampleWord.text = @"示";
                break;
            case 3:
                exampleWord.text = @"例";
                break;
            default:
                break;
        }
        [exampleWord setTextAlignment:NSTextAlignmentCenter];
        [exampleWord setFont:[UIFont systemFontOfSize:20]];
        [exampleWord setTextColor:[UIColor whiteColor]];
        [cellImageView addSubview:exampleWord];
        
        // 最上面的点击按钮
        bigImageButton = [[UIButton alloc] init];
        bigImageButton.tag = 5678 + i;
        [bigImageButton setFrame:rect];
        [bigImageButton addTarget:self action:@selector(actionExample:) forControlEvents:UIControlEventTouchUpInside];
        [cellImageView addSubview:bigImageButton];
    }
}

- (void)addOneImage:(UIButton *)sender {
    selectImage = [sender tag] - 22;
    
    if (![self.view viewWithTag:2222 + selectImage].isHidden) {
        // 查看已有图片的大图
        thisisimport = 0;
        UIView *view;
        NSMutableArray *images = [[NSMutableArray alloc] init];
        for (int i = 1111; i < 1115; i++) {
            view = [self.view viewWithTag:i];
            UIImageView *imageView = (UIImageView *)[view viewWithTag:i - 1111 + 11];
            if (![self.view viewWithTag:i - 1111 + 2222].isHidden) {
                UIImage *image = imageView.image;
                [images addObject:image];
            } else {
                if ((i - 1111) < selectImage) {
                    thisisimport++;
                }
            }
        }
        
        NSLog(@"****%d", thisisimport);
        [self fourImageShowInScroll:images];
    } else {
        // 选择本地图片或者拍照
        [self paiZhao:sender];
    }
}

// 删除图片的时候给提示框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"****%d", buttonIndex);
    if (alertView.tag == 88) {
        if (buttonIndex == 1) {
            return;
        } else {
            selectImage = deleteButton.tag - 2222;
            [deleteButton setHidden:YES];
            
            UIView *view = [self.view viewWithTag:1111 + selectImage];
            UIImageView *imageView = (UIImageView *)[view viewWithTag:11 + selectImage];
            imageView.image = [UIImage imageNamed:@"noImage"];
            UIButton *button = (UIButton *)[view viewWithTag: 22 + selectImage];
            [button setBackgroundImage:[UIImage imageNamed:@"dianjishangchuan"] forState:UIControlStateNormal];
            [button setBackgroundImage:[UIImage imageNamed:@"dianjishangchuan"] forState:UIControlStateHighlighted];
            
            allNumberOfImage--;
            if (allNumberOfImage <= 0) {
                self.navigationItem.rightBarButtonItem.tintColor = HexRGB(0xf00);
                [self.navigationItem.rightBarButtonItem setEnabled:NO];
            }
            selectImage = 123456;
        }
    }
}

- (void)deleteOneImage:(UIButton *)sender {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定删除吗？" message:@"删除后需要重新拍照或者添加图片哦！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alert.tag = 88;
    [alert show];
    
    deleteButton = sender;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (IBAction)paiZhao:(UIButton *)sender {
    UIActionSheet *sheet;
    // 判断是否支持相机
    if(isCamera)
    {
        sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册选择", nil];
    }
    else {
        sheet  = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
    }
    [sheet showInView:self.view];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 2) {
        return;
    }
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;

    NSUInteger sourceType = 0;
    if (isCamera) {
        switch (buttonIndex) {
            case 0:
            {
                // 相机
                sourceType = UIImagePickerControllerSourceTypeCamera;
                
                imagePickerController.allowsEditing = NO;
                imagePickerController.sourceType = sourceType;
                [imagePickerController setShowsCameraControls:YES];
                //让相机显示全屏
                CGSize screenBounds = [UIScreen mainScreen].bounds.size;
                CGFloat scale = 4.0f/3.0f;
                CGFloat camViewHeight = screenBounds.height / scale;
                imagePickerController.cameraViewTransform = CGAffineTransformMakeTranslation(0, Kheight/2 - 45 - camViewHeight/2);
                imagePickerController.cameraViewTransform = CGAffineTransformScale(imagePickerController.cameraViewTransform, scale + 0.1, scale + 0.1);
            }
                break;
            case 1:
            {
                // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }
                break;
            default:
                break;
        }
    } else {
        switch (buttonIndex) {
            case 0:
            {
                // 相册
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            }
                break;
            default:
                return;
                break;
        }
    }

    [self presentViewController:imagePickerController animated:YES completion:^{
    }];
}

#pragma markUIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIView *view = [self.view viewWithTag:1111 + selectImage];
    UIImageView *imageView = (UIImageView *)[view viewWithTag:11 + selectImage];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    imageView.image = image;
    
    allNumberOfImage++;
    [[self.view viewWithTag:2222 + selectImage] setHidden:NO];
    // 隐藏添加按钮
    UIButton *button = (UIButton *)[view viewWithTag: 22 + selectImage];
    [button setBackgroundImage:nil forState:UIControlStateNormal];
    [button setBackgroundImage:nil forState:UIControlStateHighlighted];
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {// 拍照的图片获取
//        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }
    
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    
    if (allNumberOfImage >= 0) {
        self.navigationItem.rightBarButtonItem.tintColor = HexRGB(0x2AADEA);
        [self.navigationItem.rightBarButtonItem setEnabled:YES];
    }
    selectImage = 123456;
}
    
//保存照片成功后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
contextInfo:(void *)contextInfo{
    NSLog(@"saved..");
}

- (void)actionExample:(UIBarButtonItem *)sender {
    selectImage = sender.tag - 5678;
    thisisimport = 0;
    NSMutableArray *images = [[NSMutableArray alloc] init];
    for(int i = 0; i < 4; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"example%d", i + 1]];
        [images addObject:image];
    }
    [self fourImageShowInScroll:images];
}

// 将图片添加到scroll上面进行左右滚动
- (void)fourImageShowInScroll:(NSArray *) images {
    UIImageView *imageView;
    int currentNum = 0;
    
    // 将已经展示的图片清理掉
    for(UIView *view in [fourImageShow subviews]) {
        if (view.tag >= 9999 && view.tag <= 10002) {
            [view removeFromSuperview];
        }
    }
    for(UIImage *image in images) {
        imageView = [[UIImageView alloc] init];
        imageView.tag = 9999 + currentNum;
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [imageView setFrame:CGRectMake(Kwidth * currentNum, 0, Kwidth, Kheight)];
        imageView.image = image;
        [fourImageShow addSubview: imageView];
        currentNum ++;
    }

    [fourImageShow setContentSize:CGSizeMake(Kwidth * images.count, Kheight)];
    if (selectImage < 10) {
        [fourImageShow setContentOffset:CGPointMake(Kwidth * (selectImage - thisisimport), 0)];
    }
    thisisimport = 0;
    [fourImageShow setHidden: NO];
}

// 点击手势，用与消失图片展示页面
- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    [fourImageShow setHidden:YES];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"toTwoAction"]) {
        UIViewController *twoViewController = segue.destinationViewController;
        if ([twoViewController respondsToSelector:@selector(setListView:)]) {
            // 获取用户添加的图片，作为用户信息的一部分传入下一个页面并上传数据库
            UIView *view;
            NSMutableArray *images = [[NSMutableArray alloc] init];
            for (int i = 1111; i < 1115; i++) {
                view = [self.view viewWithTag:i];
                UIImageView *imageView = (UIImageView *)[view viewWithTag:i - 1111 + 11];
                if (![self.view viewWithTag:i - 1111 + 2222].isHidden) {
                    UIImage *image = imageView.image;
                    [images addObject:image];
                }
            }
            listView.privacyImages = images;
            [twoViewController setValue:listView forKey:@"listView"];
        }
        
    }
}
@end
